<!DOCTYPE html>
<html class="x-admin-sm">
<head>
    <meta charset="UTF-8">
    <title>欢迎页面-X-admin2.2</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi" />
    <!-- 让IE8/9支持媒体查询，从而兼容栅格 -->
    <!--[if lt IE 9]>
    <!--<script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>-->
    <!--<script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>-->
    <!--[endif]-->
    <script type="text/javascript" src="../../common/js/public.js"></script>
    <script type="text/javascript" src="../../common/js/publicUtils.js"></script>
    <!--<![endif]&ndash;&gt;-->
    <style>
        .menudiv .layui-input-inline,.buttondiv .layui-input-inline {
            float: left;
            width: 450px !important;
            margin-right: 10px;
        }
        #permissiondiv,.submitdiv{
            display: none;
        }
        .error{
            color: red;
            line-height: 20px;
        }

        .ztreeuldiv {
            height: 100%;
            width: 100%;
            background-color: white;
        }

    </style>
</head>
<body>
<div class="layui-fluid" id="flowDiv" onload="onLoad()">
    <div class="zTreeBackground left" style="float: left;width:300px">
        <div class="titlediv">
            <p style="text-align:right;background-color:white;line-height: 30px">
                菜单管理<i class="layui-icon layui-icon-refresh" style="margin-left: 36%" onclick="searchByName()"></i>&ensp;&ensp;
            </p>

        </div>
        <div class="searchdiv" >
            <div class="layui-input-inline" style="width:100%">
                <input type="text" id="search" name="keyword" autocomplete="off" class="layui-input" placeholder="请输入名称"/>
                <i class="layui-icon layui-icon-search" style="position: absolute;top:8px;right: 8px;" onclick="searchByName()"></i>
            </div>
        </div>
        <div class="ztreediv" id="ztreediv" style="overflow:auto">
            <div class="ztreeuldiv">
                <ul id="treeStructure" class="ztree"></ul>
            </div>
        </div>
    </div>
    <div class="zTreeBackground right" style="float: left;width:65%; padding-left:5%">
        <div id="buttongroup">

        </div>
        <div class="menudiv" style="clear: both;margin-top: 10px;">
            <fieldset class="layui-elem-field layui-field-title" style="margin-top: 60px;">
                <legend id="menunameid">菜单</legend>
            </fieldset>

            <form class="layui-form"  id="menuform" lay-filter="menuform">
                <input type="hidden" name="id">
                <div class="layui-form-item">
                    <label class="layui-form-label" for="name"><span style="color: red;">*</span>菜单名称</label>
                    <div class="layui-input-inline">
                        <input type="text" name="name" id="name" lay-verify="title" autocomplete="off" placeholder="请输入菜单名称" class="layui-input" readonly/>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label" for="pname">父级菜单</label>
                    <div class="layui-input-inline">
                        <input type="text" name="pname" id="pname" autocomplete="off" class="layui-input pname" readonly/>
                        <input type="hidden" class="pid" name="pid">
                        <div class="parentmenu"  name="parentmenu" style="position:absolute;z-index: 999;background-color: white;width: 300px;height: 300px;overflow: auto;display: none" >
                            <ul id="treeMenuInput" class="ztree"></ul>
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label" for="url"><span style="color: red;">*</span>菜单地址</label>
                        <div class="layui-input-inline">
                            <input type="text" name="url" id="url" autocomplete="off" class="layui-input" readonly/>
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label" for="sort"><span style="color: red;">*</span>排&emsp;&emsp;序</label>
                        <div class="layui-input-inline">
                            <input type="text" name="sort" id="sort" autocomplete="off" class="layui-input" readonly/>
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label" for="icon"><span style="color: red;">*</span>图&emsp;&emsp;标</label>
                        <div class="layui-input-inline">
                            <input type="text" name="icon" id="icon" autocomplete="off" class="layui-input" readonly />
                        </div>
                    </div>
                </div>
                <div class="layui-form-item" id="permissiondiv">
                    <div class="layui-inline">
                        <label class="layui-form-label" for="permission">权限标识</label>
                        <div class="layui-input-inline">
                            <input type="text" name="permission" id="permission" autocomplete="off" class="layui-input" readonly />
                        </div>
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label" for="comment">备&emsp;&emsp;注</label>
                        <div class="layui-input-inline">
                            <textarea name="comment" id="comment" placeholder="请输入备注内容" class="layui-textarea" readonly></textarea>
                        </div>
                    </div>
                </div>
            </form>
        </div>
        <div class="submitdiv">
            <button type="button" class="layui-btn layui-btn-normal" onclick="saveMenu(1)"><i class="layui-icon">&#xe608;</i>保存</button>
            <button type="button" class="layui-btn layui-btn-normal" onclick="saveMenu()"><i class="layui-icon">&#xe608;</i>应用</button>
            <button type="button" class="layui-btn layui-btn-normal" onclick="cancle()"><i class="layui-icon">&#xe608;</i>取消</button>
        </div>
    </div>
</div>
</body>
<script type="text/javascript">

    var zTreeObj,zTreeObj_input,zTreeObj_input_button,form;
    var menuid;//点击当前项数据id

    layui.use(["form"],function () {
        form = layui.form;
    })
    $(document).ready(function(){
        loadTree();
        loadbutton();//加载按钮loadbutton(id)，id为button容器id，不传默认为buttongroup
    });
    window.onload = getContentSize;
    window.onresize = getContentSize;

    /**
     * 页面自适应
     */
    function getContentSize() {
        var wh = document.documentElement.clientHeight;
        var eh = 30;
        ch = (wh - eh) + "px";
        document.getElementById( "flowDiv" ).style.height = ch;
        document.getElementById( "ztreediv" ).style.height = (wh - eh - 50)+"px";
        document.body.style.height = (wh)+"px";
    }
    /**
     * 左侧树设置
     * @type {{check: {enable: boolean}, data: {simpleData: {enable: boolean, idKey: string, pIdKey: string, isParent: string, rootPid: number}}, callback: {beforeClick: zTreeBeforeClick, onClick: zTreeOnClick}}}
     */
    var url = publicUrl+"sysmenu/selectMenuByPid";
    var setting = {
        check: {
            enable: true,
            chkboxType: { "Y": "s", "N": "s" }
        },
        edit:{
            enable: false,
        },
        async: {
            enable: true,
            url: url,
            headers: {"Authorization":getData("Authorization")},
            dataFilter: formatedata,
            otherParam:{//传入查询参数
                //注意，要传入动态变化的参数必须用return的方式
                "name":function(){return $("#search").val()
                }
            },

            autoParam: ["id"]
        },
        data: {
            simpleData: {
                enable: true,
                idKey:"id",
                pIdKey:"pid",
                isParent:"parent",
                rootPid:-1
            },
            key: {
                isParent:"parent",
                url: "xUrl",
                icon:"xIcon"
            }
        },
        callback: {
            beforeClick: zTreeBeforeClick,
            onClick: zTreeOnClick
        }
    };
    /**
     * @Author bxf
     * @Description 搜索框按钮
     * @Date 11:20 2019/7/17
     * @Param 
     * @return 
     **/
    function searchByName(){
        loadTree();
    }

    /**
     * 点击前验证
     * @param treeId
     * @param treeNode
     * @param clickFlag
     * @returns {boolean}
     */
    function zTreeBeforeClick(treeId, treeNode, clickFlag) {
        return (treeNode.id !== menuid);
    };
    /**
     * 加载左侧树
     */
    function loadTree(){
        zTreeObj = $.fn.zTree.init($("#treeStructure"), setting, null);

    }

    /**
     * 数据拦截器
     * @param treeId
     * @param parentNode
     * @param responseData
     */
    function formatedata(treeId,parentNode,responseData) {
        return formatTreeParseData(treeId,parentNode,responseData,null);
    }

    /**
     * 点击触发
     * @param event
     * @param treeId
     * @param treeNode
     */
    function zTreeOnClick(event, treeId, treeNode) {
        if($("#editMenu")){
            $("#editMenu").attr("onclick","editMenu(this)");
            $("#editMenu").html("<i class='layui-icon'>&#xe608;</i>编辑");
        }
        menuid = treeNode.id;
        var paname = "";
        if(treeNode.getParentNode()){
            paname = treeNode.getParentNode().name;
        }
        if(treeNode.type==1){
            $("#menunameid").text("菜单");
            addMenu();
            $(".submitdiv").css("display","none");
            form.val("menuform",{
                "name":treeNode.name,
                "pname":paname,
                "pid":treeNode.pid,
                "url":treeNode.url,
                "sort":treeNode.sort,
                "icon":treeNode.icon,
                "comment":treeNode.comment,
                "id":treeNode.id
            })
        }else{
            $("#menunameid").text("按钮");
            addButton();
            $(".submitdiv").css("display","none");
            form.val("menuform",{
                "name":treeNode.name,
                "pname":paname,
                "pid":treeNode.pid,
                "url":treeNode.url,
                "sort":treeNode.sort,
                "icon":treeNode.icon,
                "comment":treeNode.comment,
                "id":treeNode.id
            })
        }
        addreadonly();
    };

    /**
     * input输入框中树
     * @type {{data: {simpleData: {enable: boolean, idKey: string, pIdKey: string, isParent: string, rootPid: number}}, callback: {onClick: zTreeInputOnClick}}}
     */
    var input_setting = {
        data: {
            simpleData: {
                enable: true,
                idKey:"id",
                pIdKey:"pid",
                isParent:"parent",
                rootPid:-1
            },
            key: {
                isParent:"parent",
                url: "xUrl",
                icon:"xIcon"
            }
        },
        callback: {
            onClick: zTreeInputOnClick
        }
    };

    /**
     * 点击触发
     * @param event
     * @param treeId
     * @param treeNode
     */
    function zTreeInputOnClick(event, treeId, treeNode) {
        $(".pname").val(treeNode.name);
        $(".pid").val(treeNode.id);
        $(".parentmenu").css("display","none");
        $(validform(1).form());
    };

    /**
     * 加载input中树
     */
    function loadInputTree(){
        if($(".parentmenu").css("display")=="block"){
            $(".parentmenu").css("display","none");
        }else{
            $(".parentmenu").css("display","block");
            publicAjax (null,"sysmenu/selectAllMenu",{},null,null,function(r){
                var jsondata = r.data;
                var json = {"id":-1,"name":"菜单管理", open:true};
                jsondata.push(json);
                zTreeObj_input = $.fn.zTree.init($("#treeMenuInput"),input_setting , jsondata);
                getAppointNode(zTreeObj_input,$(".menudiv pid").val());
            })
        }

    }



    /**
     * 打开选中指定节点
     * @param treeobj
     * @param id
     */
    function getAppointNode(treeobj,id){
        if(id){
            var node = treeobj.getNodeByParam("id",id);
            treeobj.selectNode(node,true);//指定选中ID的节点
            treeobj.expandNode(node, true, false);//指定选中ID节点展开
        }
    }


    //编写表单验证函数validform，在验证按钮注册按钮点击事件内调用验证函数对象
    function validform(flag){
        /*关键在此增加了一个return，返回的是一个validate对象，这个对象有一个form方法，返回的是是否通过验证*/
            jQuery.validator.addMethod("permissionV",function(value,element,param){
                var obj = true;
                if(!value){
                    return obj;
                }else{
                    publicAjax (null,"sysmenu/selectMenuByIdAndPermisson",{"id":$("#id").val(),"permission":value},false,null,function (r) {
                        if(r.code==2000){
                            if(flag==1){//保存
                                if(r.data>0){
                                    obj = false;
                                }else{
                                    obj = true;
                                }
                            }else{//更新
                                if(r.data>1){
                                    obj = false;
                                }else{
                                    obj = true;
                                }
                            }

                        }else{
                            obj = false;
                        }
                    })
                    return obj;
                }
            },"该权限标记系统已存在");
            return $("#menuform").validate({
                rules : {
                    name : {
                        required:true,
                        normalizer: function( value ) {
                            return $.trim( value );
                        }
                    },
                    pname: {
                        required:true,
                        normalizer: function( value ) {
                            return $.trim( value );
                        }
                    },
                    icon: {
                        required:true,
                        normalizer: function( value ) {
                            return $.trim( value );
                        }
                    },
                    sort: {
                        required:true,
                        number:true,
                        normalizer: function( value ) {
                            return $.trim( value );
                        }
                    },
                    permission:{
                        permissionV: true,
                        normalizer: function( value ) {
                            return $.trim( value );
                        }
                    },
                    comment: {
                        maxlength: 100,
                        normalizer: function( value ) {
                            return $.trim( value );
                        }
                    },
                },
                messages : {
                    name : {
                        required: "菜单名称不能为空"
                    },
                    pname : {
                        required: "请选择父类菜单"
                    },
                    sort : {
                        required:"请输入有效的数字",
                        number: "请输入有效的数字",
                    },
                    icon : {
                        required: "请选择图标"
                    },
                    permission:{
                        permissionV: "该权限标记系统已存在",
                    },
                    comment : {
                        maxlength: "备注长度不可超过100"
                    }
                }
            });

    }

    /**
     * @Author bxf
     * @Description 清除验证消息
     * @Date 17:58 2019/7/18
     * @Param 
     * @return 
     **/
    function ignorevalidate(){
        validform(1).resetForm();
    }
    /**
     * @Author bxf
     * @Description 增加制度属性
     * @Date 11:22 2019/7/17
     * @Param 
     * @return 
     **/
    function addreadonly(){
        $("#menuform").find("input").attr("readonly",true);
        $("#menuform").find("textarea").attr("readonly",true);
    }
    /**
     * @Author bxf
     * @Description 移除制度属性
     * @Date 11:22 2019/7/17
     * @Param
     * @return
     **/
    function removereadonly() {
        $("#menuform").find("input").removeAttr("readonly");
        $("#menuform").find("textarea").removeAttr("readonly");
        $("#pname").attr("readonly",true);
    }
    /**
     * @Author bxf
     * @Description 选择icon
     * @Date 11:22 2019/7/17
     * @Param
     * @return
     **/
    var resultData;
    function selectIcon(callback){
        if(isEmpty(callback)){
            callback = function(index, layero) {
                var iframeWin = layero.find('iframe')[0];
                resultData = iframeWin.contentWindow.submit(index, layero);
                $("#icon").val(resultData);
                layer.closeAll();
            }
        }
        layer.open({
            type: 2,
            area: ['700px', '550px'],
            fix: false,
            //不固定
            maxmin: true,
            shade: 0.3,
            title: "icon选择",
            content: "./buttonIcon.html",
            btn: ['确定', '关闭'],
            // 弹层外区域关闭
            shadeClose: false,
            yes: callback,
            cancel: function(index) {
                return true;
            }
        });
    }
    /**
     * @Author bxf
     * @Description 判断是都为空
     * @Date 11:23 2019/7/17
     * @Param
     * @return
     **/
    function isEmpty(value) {
        if (value == null || this.trim(value) == "") {
            return true;
        }
        return false;
    }



    /**
     * 保存菜单
     */
    function saveMenu(val){
        var obj ;
        var menuflag = $("#permissiondiv").css("display");
        var formData = new FormData($("#menuform")[0]);;
        if(menuflag=="none"){
            formData.set("type","1");
        }else{
            formData.set("type","2");
        }
        obj = $(validform(1).form());
        if(obj[0]){
            formData.delete("id");
            publicAjaxFormData(null,"sysmenu/insertMenu",formData,null,null,function(data){
                if(data.code==2000){
                    laysuccess("保存成功！",1000);
                    if(val==1){
                        form.val("menuform",{
                            "name":"",
                            "pname":"",
                            "pid":"",
                            "url":"",
                            "sort":"",
                            "permission":"",
                            "icon":"",
                            "comment":"",
                            "id":""
                        });
                    }
                    refreshSelectNode(zTreeObj,formData.get("pid"));
                }else{
                    layerror("保存失败！",1000);
                }
            })
        }
    }

    /**
     * 更新菜单
     */
    function updateMenu(val){
        var obj ;
        var menuflag = $("#permissiondiv").css("display");
        var formData = new FormData($("#menuform")[0]);;
        if(menuflag=="none"){
            formData.set("type","1");
        }else{
            formData.set("type","2");
        }
        obj = $(validform(2).form());//按钮验证
        if(obj[0]){
            publicAjaxFormData(null,"sysmenu/updateMenu",formData,null,null,function(data){
                if(data.code==2000){
                    laysuccess("更新成功！",1000);
                    $(val).attr("onclick","editMenu(this)");
                    $(val).html("<i class='layui-icon'>&#xe608;</i>编辑");
                    addreadonly();
                    refreshSelectNode(zTreeObj,formData.get("pid"));
                }else{
                    layerror("更新失败！",1000);
                }
            })
        }
    }

    /**
     * @Author bxf
     * @Description 切换添加菜单功能
     * @Date 14:27 2019/7/16
     * @Param 
     * @return 
     **/
    function addMenu(){
        form.val("menuform",{
            "name":"",
            "url":"",
            "sort":"",
            "permission":"",
            "icon":"",
            "comment":"",
            "id":""
        });
        $("#icon").attr("onClick","");
        $("#permissiondiv").css("display","none");
        $(".submitdiv").css("display","block");
        $("#pname").attr("onClick","loadInputTree()");
        $("#menunameid").text("菜单");
        ignorevalidate();
        removereadonly();
    }
    /**
     * @Author bxf
     * @Description 切换添加按钮功能
     * @Date 14:28 2019/7/16
     * @Param 
     * @return 
     **/
    function addButton(){
        form.val("menuform",{
            "name":"",
            "url":"",
            "sort":"",
            "permission":"",
            "icon":"",
            "comment":"",
            "id":""
        });
        $("#menunameid").text("按钮");
        $("#permissiondiv").css("display","block");
        $("#icon").attr("onClick","selectIcon()");
        $(".submitdiv").css("display","block");
        $("#pname").attr("onClick","loadInputTree()");
        ignorevalidate();
        removereadonly();
    }
    /**
     * @Author bxf
     * @Description 编辑切换按钮
     * @Date 11:23 2019/7/17
     * @Param 
     * @return 
     **/
    function editMenu(val){
        removereadonly();
        $(val).attr("onclick","updateMenu(this)");
        $(val).attr("id","editMenu");
        $(".submitdiv").css("display","none");
        $("#pname").attr("onClick","loadInputTree()");
        $(val).html("<i class='layui-icon'>&#xe608;</i>保存");
    }
    /**
     * @Author bxf
     * @Description 取消按钮局
     * @Date 11:40 2019/7/17
     * @Param 
     * @return 
     **/
    function cancle(){
        $(".submitdiv").css("display","none");
        $("#pname").attr("onClick","");
        addreadonly();
        form.val("menuform",{
            "name":"",
            "pname":"",
            "pid":"",
            "url":"",
            "sort":"",
            "permission":"",
            "icon":"",
            "comment":"",
            "id":""
        });
    }

    function getSelectNode(){
        console.info(zTreeObj.getSelectedNodes())
    }
    
    function  deleteNode() {
        //获取选中项
        var nodes = zTreeObj.getCheckedNodes(true);
        var ids = new Array();
        if(nodes.length<1){
            layself('请至少选择一项信息',1000,3);
            return false;
        }
        for(var i=0;i<nodes.length;i++){
            ids.push(nodes[i].id);
        }
        layui.use(['layer'],function(){
            var layer = layui.layer;
            layer.confirm('删除父类子类会级联删除，确定删除？', {
                btn: ['确定', '取消'] //可以无限个按钮
            }, function(){
                publicAjax (null,"sysmenu/deleteMenuByIds",{"ids":ids.join(",")},null,null,function(data){
                    if(data.code==2000){
                        laysuccess("删除成功！",1000);
                        zTreeObj = $.fn.zTree.init($("#treeStructure"), setting, null);
                    }else{
                        layerror("删除失败！",null);
                    }
                })
            }, function(){
                layer.closeAll();

            });

        })
    }

    /**
     * 刷新指定节点
     */
    function refreshSelectNode(obj,id) {
        menuid = "";
        var node = obj.getNodeByParam("id",id);
         zTreeObj.reAsyncChildNodes(node,"refresh");
    }


</script>
</html>